//
//  NSDate+LHCalender.m
//  calender
//
//  Created by zhouLiHuan on 2017/1/20.
//  Copyright © 2017年 zhouLiHuan. All rights reserved.
//

#import "NSDate+LHCalender.h"

@implementation NSDate (LHCalender)


/**
 获取当前NSData对应的日子
 */
- (NSInteger)dateDay{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components  = [calendar components:NSCalendarUnitDay fromDate:self];
    return components.day;
    
}

/**
 获取当前 NSDate对应的月份
 */

- (NSInteger)dateMonth{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitMonth fromDate:self];
    return components.month;
}

/**
 获取当前 NSDate对应的年份
 */
- (NSInteger)dateYear{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear fromDate:self];
    return components.year;
}

/**
 获取当前 NSDate 对象的上一个月的某一天(此处定为15号)的NSDate 对象
 */

- (NSDate *)previousMonthDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self];
    components.day = 15; //定位到当月中间的日子
    if (components.month == 1) {
        components.month = 12;
        components.year = -1;
    }else{
        components.month -= 1;
    }
    NSDate *previousDate = [calendar dateFromComponents:components];
    return previousDate;
}


/**
 获取当前 NSDate 对象下一个月的某一天 (此处为15号)的NSDate 对象
 */

- (NSDate *)nextMonthDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self];
    components.day = 15; //定位到当月中间日子
    if (components.month == 12) {
        components.month = 1;
        components.year += 1;
    }else {
        components.month += 1;
    }
    
    NSDate *nextDate = [calendar dateFromComponents:components];
    return nextDate;
}


/**
 获取当前 NSDate对象对应的月份的总天数
 */
- (NSInteger)totalDaysInMonth{
    
    NSInteger totalDays = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self].length;
    return totalDays;
    
}



 /**
 获取当前 NSDate对象对应的月份当月第一天的所属星期
 */

- (NSInteger)firstWeekDayInMonth{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self];
    components.day = 1;
    NSDate *firstDay = [calendar dateFromComponents:components];
    
    //默认一周第一天序号为1 而日历中约定为0 故需减一
    NSInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDay] - 1;
    return firstWeekday;
    
}
@end

